package com.topisv.tms.web.work.express;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ExpressStyle;
import com.topisv.tms.entity.PackformStyle;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.repository.EdiOrderItemDao;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ExpressStyleService;
import com.topisv.tms.service.PackformStyleService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.utils.enums.StatusEnums;
//import com.topisv.tms.utils.http.SynchroShippedBatchQueue;

/**
 * 运单打印_control
 * @author caomingwu
 */
@Controller
@RequestMapping(value = "/v2/express")
public class ExpressController {

	private static final Logger logger = LoggerFactory.getLogger(ExpressController.class);

	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private PackformStyleService packformStyleService;
	@Autowired
	private ExpressStyleService expressStyleService;
	@Autowired
	private EdiOrderService ediOrderService ;
	@Autowired
	private EdiOrderItemDao ediOrderItemDao ;
	
	
	/**
	 * 导向包装页面_预先打单
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toPkgPage_prePrint")
	public String toPkgPage_prePrint(ServletRequest request,HttpServletResponse response,Model model){
		return "work/pkg/pkg_prePrint";
	}

	/**
	 * 导向订单打印
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toExpressBillPrint")
	public String toExpressBillPrint(ServletRequest request,HttpServletResponse response,Model model){
		
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	    String customerCode=curUser.customerCode;
	    Customers customer=this.customersService.findByCustomerCode(customerCode);
	    model.addAttribute("customer", customer); 
	    
		return "work/expressBill/expressBillPrint";
	}
	
	/**
	 * 导向包装页面_及时打单_单件
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toPkgPage_intimePrint_single")
	public String toPkgPage_intimePrint_single(ServletRequest request,HttpServletResponse response,Model model){
		
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	    String customerCode=curUser.customerCode;
	    Customers customer=this.customersService.findByCustomerCode(customerCode);
	    model.addAttribute("customer", customer); 
	    
		return "work/pkg/pkg_intimePrint_single";
	}
	
	/**
	 * 导向包装页面_及时打单_多件
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toPkgPage_intimePrint_multi")
	public String toPkgPage_intimePrint_multi(ServletRequest request,HttpServletResponse response,Model model){
		
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	    String customerCode=curUser.customerCode;
	    Customers customer=this.customersService.findByCustomerCode(customerCode);
	    model.addAttribute("customer", customer); 
	    
		return "work/pkg/pkg_intimePrint_multi";
	}
	
	
	/**
	 * ajax查询订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxQueryOrder")
	public void ajaxQueryOrder(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		try {
			
			out = response.getWriter();
			json = new JSONObject();
			
			String orderno=request.getParameter("orderno");
			
			WorkOrder workOrder=this.workOrderService.loadOrderByOrderno(orderno);
			
			if(workOrder==null){
				msg="noexist"; //不存在此订单
			}else{
				
				if(!workOrder.getStatus().equals("9")){
					msg="notPkg"; //不在包装状态
				}else{
					msg="checkPass";
					json.put("workOrder", workOrder);
				}
				
			}
			json.put("msg", msg);
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}
	}
	
	
	/**
	 * 包装
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxPkg")
	public void ajaxPkg(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		
		try {	
			
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			String orderno=request.getParameter("orderno"); 
		    msg=this.workTaskService.pkg(orderno,curUser.jobuuid);
		    if("success".equals(msg)){
		    	try {
		    		WorkOrder workOrder=this.workOrderService.loadOrderByOrderno(orderno);
		    		/*
		    		 * 去掉推送数据到圆通的流程
					if("ebill".equals(workOrder.getBillType())){
						 if("YTO".equals(workOrder.getExpressCompany())){
							  if(!"create".equals(workOrder.getEbillStatus())){
								  SynchroShippedBatchQueue.putSendMessageQueue("createOrdenoYTO"+StatusEnums.split.getStatus()+workOrder.getOrder().getOrdeno());//向圆通平台创建电子面单
							  }
						 }
					}*/
					
                   if(!"finish".equals(workOrder.getSendOutStatus())){
//                	   SynchroShippedBatchQueue.putSendMessageQueue("sendOutOrdeno"+StatusEnums.split.getStatus()+workOrder.getOrder().getOrdeno());
                   }
				} catch (Exception e) {
					
				}
		    }
			
		    json.put("msg", msg);
			out.print(json);
			
		} catch (Exception e) {
			logger.error("error",e);
			json.put("msg", "error");
			out.print(json);
		}
	}
	
	
	/**
	 * ajax根据订单编号查询订单详情
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCheckOrderInfo")
	public void ajaxCheckOrderInfo(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		try {
			
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    String warehouseCode=curUser.areagroups;
			String orderno=request.getParameter("orderno");
			
			//WorkOrder workOrder=this.workOrderService.loadOrderBySku(warehouseCode,skuInfo);findByOrderno
			WorkOrder workOrder=this.workOrderService.loadByAnyOrderno(orderno);
			if(null == workOrder.getExpressNo()){
				workOrder.setExpressNo(workOrder.getEbillNo());
			}
			List<EdiOrderItem> orderItems = this.ediOrderItemDao.findByOrdeno(workOrder.getOrder().getOrdeno());
			workOrder.getOrder().setOrderItems(orderItems);
			if(workOrder==null){
				msg="error";  //无匹配的订单数据
			}else if("cancel".equals(workOrder.getCancelStatus())){ //取消单
				msg="cancel";
				json.put("workOrder", workOrder);
			}else{
				msg="success";  //找到匹配的订单数据
				json.put("workOrder", workOrder);
				String type="ebill".equals(workOrder.getBillType())? "mail":"normal";
				//打印单模板
				List<PackformStyle> packformStyles=packformStyleService.findByCustomerCode(workOrder.getCustomerCode());// 随箱单
				
				List<ExpressStyle> expressStyles=expressStyleService.findByCustomerCodeAndAreaGroupCode(workOrder.getCustomerCode(), workOrder.getWarehouseCode()); //运单
				List<ExpressStyle> es=new ArrayList<ExpressStyle>();
				for(ExpressStyle e:expressStyles){
					if(type.equals(e.getType())){
						es.add(e);
					}
				}
				json.put("packformStyles", packformStyles);
				json.put("expressStyles", es);
			}
				
			json.put("msg", msg);
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}
	}
	/**
	 * ajax获取东莞仓置顶打印单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCheckDgExpressStyles")
	public void ajaxCheckDgExpressStyles(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		try {
			
			out = response.getWriter();
			json = new JSONObject();
			//打印单模板
			List<ExpressStyle> expressStyles=expressStyleService.findByCustomerCodeAndAreaGroupCode("TSTDG","HZTT"); //运单
			List<ExpressStyle> es=new ArrayList<ExpressStyle>();
			for(ExpressStyle e:expressStyles){
				if("mail".equals(e.getType())){
					es.add(e);
				}
			}
			if(null != es ){
				msg="success" ;
			}else{
				msg="error" ;
			}
			json.put("expressStyles", es);
				
			json.put("msg", msg);
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}
	}
	
	/**
	 * ajax根据SKU查询待包装的订单_多件
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "v2_ajaxCheckSkuInfo_multi")
	public void ajaxCheckSkuInfo_multi(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		try {
			
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    String warehouseCode=curUser.areagroups;
		    
			String skuInfo=request.getParameter("skuInfo");
			
			WorkOrder workOrder=this.workOrderService.loadOrderBySku_multi(warehouseCode,skuInfo);
			
			if(workOrder==null){
				msg="error";  //无匹配的订单数据
			}else if("cancel".equals(workOrder.getCancelStatus())){ //取消单
				msg="cancel";
				json.put("workOrder", workOrder);
			}else{
				msg="success";  //找到匹配的订单数据
				json.put("workOrder", workOrder);
				String type="ebill".equals(workOrder.getBillType())? "mail":"normal";
				//打印单模板
				List<PackformStyle> packformStyles=packformStyleService.findByCustomerCode(workOrder.getCustomerCode());// 随箱单
				
				List<ExpressStyle> expressStyles=expressStyleService.findByCustomerCodeAndAreaGroupCode(workOrder.getCustomerCode(), workOrder.getWarehouseCode()); //运单
				List<ExpressStyle> es=new ArrayList<ExpressStyle>();
				for(ExpressStyle e:expressStyles){
					if(type.equals(e.getType())){
						es.add(e);
					}
				}
				json.put("packformStyles", packformStyles);
				json.put("expressStyles", es);
			}
				
			json.put("msg", msg);
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}
	}
	
	
	
	/**
	 * ajax根据SKU查询待包装的订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "v2_ajaxCheckSkuInfo_single")
	public void ajaxCheckSkuInfo_single(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		try {
			
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    String warehouseCode=curUser.areagroups;
		    
			String skuInfo=request.getParameter("skuInfo");
			
			WorkOrder workOrder=this.workOrderService.loadOrderBySku_single(warehouseCode,skuInfo);
			
			if(workOrder==null){
				msg="error";  //无匹配的订单数据
			}else if("cancel".equals(workOrder.getCancelStatus())){ //取消单
				msg="cancel";
				json.put("workOrder", workOrder);
			}else{
				msg="success";  //找到匹配的订单数据
				json.put("workOrder", workOrder);
				String type="ebill".equals(workOrder.getBillType())? "mail":"normal";
				//打印单模板
				List<PackformStyle> packformStyles=packformStyleService.findByCustomerCode(workOrder.getCustomerCode());// 随箱单
				
				List<ExpressStyle> expressStyles=expressStyleService.findByCustomerCodeAndAreaGroupCode(workOrder.getCustomerCode(), workOrder.getWarehouseCode()); //运单
				List<ExpressStyle> es=new ArrayList<ExpressStyle>();
				for(ExpressStyle e:expressStyles){
					if(type.equals(e.getType())){
						es.add(e);
					}
				}
				json.put("packformStyles", packformStyles);
				json.put("expressStyles", es);
			}
				
			json.put("msg", msg);
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}
	}
	
	
	
	/**
	 * ajax根据订单编号、运单编号查询待包装的订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCheckWorkOrder")
	public void ajaxCheckWorkOrder(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		try {
			
			out = response.getWriter();
			json = new JSONObject();
		    
			String orderno=request.getParameter("orderno");
			String expressNo=request.getParameter("expressNo");
			String _expressNo=null;
			
			WorkOrder workOrder=this.workOrderService.loadOrderByOrderno(orderno);
			
			if(workOrder==null){ //无匹配的订单数据
				msg="error";
			}else if("cancel".equals(workOrder.getCancelStatus())){ //取消单
				msg="cancel";
				json.put("workOrder", workOrder);
			}else{
				
				if(!workOrder.getStatus().equals("9")){
					msg="error"; //不在包装环节
				}else{
					
					String billType=workOrder.getBillType();
					if(billType.equals("ebill")){
						_expressNo=workOrder.getEbillNo();
					}else if(billType.equals("cbill")){
						_expressNo=workOrder.getExpressNo();
					}
					
					if(expressNo.equals(_expressNo)){
						workOrder.setPkgLock("pkging");
						this.workOrderService.save(workOrder);
						msg="success";  //找到匹配的订单数据
						json.put("workOrder", workOrder);
					}else{
						msg="error";  //无匹配的订单数据
					}
				}
			}
			
			json.put("msg", msg);
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}
	}
	
	/**
	 * ajax根据运单编号查询待包装的订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCheckWorkOrder_2")
	public void ajaxCheckWorkOrder_2(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		try {
			
			out = response.getWriter();
			json = new JSONObject();
		    
			//String orderno=request.getParameter("orderno");
			String expressNo=request.getParameter("expressNo");
			//String _expressNo=null;
			
			//WorkOrder workOrder=this.workOrderService.loadOrderByOrderno(orderno);
			WorkOrder workOrder=this.workOrderService.loadByExpressNo(expressNo);
			
			if(workOrder==null){ //无匹配的订单数据
				msg="error";
			}else if("cancel".equals(workOrder.getCancelStatus())){ //取消单
				msg="cancel";
				json.put("workOrder", workOrder);
			}else{
				
				if(!workOrder.getStatus().equals("9")){
					msg="error"; //不在包装环节
				}else{
					/*
					String billType=workOrder.getBillType();
					if(billType.equals("ebill")){
						_expressNo=workOrder.getEbillNo();
					}else if(billType.equals("cbill")){
						_expressNo=workOrder.getExpressNo();
					}
					
					if(expressNo.equals(_expressNo)){*/
						workOrder.setPkgLock("pkging");
						this.workOrderService.save(workOrder);
						msg="success";  //找到匹配的订单数据
						json.put("workOrder", workOrder);
					/*}else{
						msg="error";  //无匹配的订单数据
					}*/
				}
			}
			
			json.put("msg", msg);
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}
	}
	
	
	/**
	 * ajax核对商品和订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCheckGoodsInfo")
	public void ajaxCheckGoodsInfo(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		try {
			
			out = response.getWriter();
			json = new JSONObject();
			
			String skuInfo=request.getParameter("skuInfo");
			String orderno=request.getParameter("orderno");
			
			msg=this.workOrderService.checkGoodsInfo(orderno,skuInfo);
				
			json.put("msg", msg);
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}
	}
	
	
	
	
}